package cn.com.yusys.yusp.admin.quartz;

import cn.com.yusys.yusp.admin.Utils.BlockQueueManager;
import cn.com.yusys.yusp.admin.Utils.Smstoone;
import com.esms.MessageData;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.BlockingQueue;

/**
 * 用户数同步UM定时
 */
public class SendMessageJob extends QuartzJobBean {
    @Value("${quartz.endTime}")
    private String endTime;

    @Autowired
    private Smstoone smstoone;

    private final Logger logger = LoggerFactory.getLogger(SendMessageJob.class);

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //定时任务
        logger.info("短信发送自定义定时任务开启......");
        logger.info(Thread.currentThread().getName());
        sendMessage(BlockQueueManager.getObject());
    }

    /**
     * FIFO原则,取出单个审批数据进行发送
     */
    public void sendMessage(BlockingQueue<List<MessageData>> blockingQueue){
        List<String> arr = new ArrayList<>();
        arr.add("dlscrm1");
        arr.add("dlscrm2");
        try {
            while (shutdowmTask()) {
                //有数据时直接从队列的队首取走，无数据时阻塞，在2s内有数据，取走，超过2s还没数据，返回失败
                List<MessageData> senddata = BlockQueueManager.get();
                if (senddata!=null) {
                    logger.info("正在消费数据包"+senddata);
//                    System.out.println("正在消费数据包"+senddata);
//                    System.out.println("<==================================================================>");
                    //生产
                    smstoone.sendMessage(senddata,arr);
                    //测试
//                    Thread.sleep(120000);//睡眠一分钟
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            System.out.println("异常捕捉信息:{"+e.getMessage()+"}");
        }

    }
    //关闭当天定时任务,每天20点关闭定时任务
    public boolean shutdowmTask(){
        boolean flag = true;
        int endHour = Integer.parseInt(endTime);
        SimpleDateFormat sdf= new SimpleDateFormat("HH");
        int time = Integer.parseInt(sdf.format(new Date()));
        if(time>=endHour){//20代表晚上20点,24小时制
            logger.info(Thread.currentThread().getName());
            Thread.currentThread().interrupt();
            logger.info("今日定时任务已经关闭!");
            flag=false;
        }
        return flag;
    }
}
